package cn.migu.music.hangupsms.cachemanage.handler;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.common.config.HangUpSmsConfig;
import cn.migu.music.hangupsms.common.entity.BlackUserInfo;
import cn.migu.music.hangupsms.dbcache.BlackUserCacheManager;
import cn.migu.music.hangupsms.dbcache.BlackUserInfoMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * @version 1.0 created by duanhao@migu.cn on 2022/3/7 2:10 下午
 */
@Component
@Slf4j
public class BusinessDbDataCacheServices {

    public static final String    ISBLACK      = "1";
    @Autowired
    private BlackUserInfoMapper   blackUserInfoMapper;
    @Autowired
    private HangUpSmsConfig       hangUpSmsConfig;
    @Autowired
    private BlackUserCacheManager blackUserCacheManager;
    private Map<String, String>   blackUserMap = Collections.emptyMap();

    @PostConstruct
    public void init() {
        // 这里做加载操作
        initBlackUserMap();
    }

    private void initBlackUserMap() {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return;
        }
        LogUtils.info(log, "load black user from db start!");
        List<BlackUserInfo> userDataList;
        // 查询被叫/主叫销户满31天用户
        int sum = blackUserInfoMapper.selectCount();
        Map<String, String> temp = new HashMap<>(sum);
        String phoneNumber = "0";
        do {
            userDataList = blackUserInfoMapper.selectByPage(phoneNumber, hangUpSmsConfig.getQueryBlackUserPageSize());
            for (BlackUserInfo user : userDataList) {
                phoneNumber = user.getPhonenumber();
                temp.put(user.getPhonenumber(), ISBLACK);
            }
        } while (!CollectionUtils.isEmpty(userDataList) && userDataList.size() >= hangUpSmsConfig.getQueryBlackUserPageSize());

        this.blackUserMap = temp;
        LogUtils.info(log, "load black user from db end!");
    }

    public int getPageSum(int sum, int dataSize) {
        return sum % dataSize != 0 ? (sum / dataSize) + 1 : (sum / dataSize);
    }

    public boolean isBlackNum(String num) {
        if (hangUpSmsConfig.isBlackUserCacheSwitchOn()) {
            return blackUserCacheManager.isBlack(num);
        }
        return StringUtils.isNotEmpty(blackUserMap.get(num));
    }
}
